package com.fujimana.rockincat.restree.phase;

import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.fujimana.rockincat.restree.init.Init;
import com.fujimana.rockincat.restree.service.Response;
import com.fujimana.rockincat.restree.util.HttpUtils;
import com.fujimana.rockincat.restree.util.HttpUtils.HttpHeader;

public class NegotiationPhase implements Phase {

	@Override
	public void execute(Map<String, Object> context) {
		Init init = (Init) context.get(Init.class.getName());
		HttpServletRequest request = (HttpServletRequest) context
				.get(HttpServletRequest.class.getName());

		String mime = HttpUtils.negotiationContent(request
				.getHeader(HttpHeader.ACCEPT), init.getSupporttedResponseContentType());
		Locale locale = HttpUtils.negotiationLocation(request
				.getHeader(HttpHeader.ACCEPT_LANGUAGE), init
				.getSupportedLocal());
		String charset = HttpUtils.negotiationCharaset(request
				.getHeader(HttpHeader.ACCEPT_CHARSET), init
				.getSupportedCharset());

		context.put("contentType", mime);
		context.put("locale", locale);
		context.put("charset", charset);

		Response.getResponse().setCharset(charset);
		Response.getResponse().setContentType(mime);
		Response.getResponse().setLocale(locale);

	}

	@Override
	public String getId() {
		return NegotiationPhase.class.getSimpleName();
	}

	@Override
	public boolean isChain() {
		return true;
	}
}
